package com.test.java8;

import java.util.concurrent.locks.StampedLock;

/**
 * StampedLock使用 Java8读写锁的升级版本
 * 
 * @author xuguangqiao
 *
 */
public class Point {

	private double x, y;
	private final StampedLock lock = new StampedLock();

	void move(double deltaX, double deltaY) {// 这是一个排他锁
		long stamp = lock.writeLock();
		try {
			x += deltaX;
			y += deltaY;
		} finally {
			lock.unlockWrite(stamp);
		}
	}

	double distanceFromOrigin() {
		long stamp = lock.tryOptimisticRead();// 只读方法,客观读取锁
		double currentX = x, currentY = y;
		if (!lock.validate(stamp)) {//校验是否有效
			stamp = lock.readLock();
			try {
				currentX = x;
				currentY = y;
			} finally {
				lock.unlockRead(stamp);
			}
		}

		return Math.sqrt(currentX * currentX + currentY * currentY);
	}
}
